import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { listTeamApi, updateInfoApi } from '../api/team'

const currentTeamName = ref()
const currentTeam = ref({})
const teamList = reactive({
  arr: []
})
const editTeamForm = reactive({})
const editTeamVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(0x7fffffff)

async function getTeamList() {
  const { data: res } = await listTeamApi(currentPage.value, pageSize.value)
  teamList.arr = res.data.records
  currentTeam.value = teamList.arr[0] ? teamList.arr[0] : {}
  currentTeamName.value = currentTeam.value.name
}
async function editTeam() {
  const { data: res } = await updateInfoApi(editTeamForm)
  if (!res.success) {
    ElMessage.error({
      message: res.msg,
      dangerouslyUseHTMLString: true
    })
    return
  }
  Object.assign(currentTeam.value, editTeamForm)
  ElMessage.success(res.data)
  editTeamVisible.value = false
}

function updateCurrentTeam() {
  for (let i = 0; i < teamList.arr.length; i++) {
    if (teamList.arr[i].name === currentTeamName.value) {
      currentTeam.value = teamList.arr[i]
      break
    }
  }
}
function preEditTeam() {
  Object.assign(editTeamForm, currentTeam.value)
  editTeamVisible.value = true
}

export const useTeam = () => {
  return {
    currentTeamName,
    currentTeam,
    teamList,
    editTeamForm,
    editTeamVisible,
    getTeamList,
    updateCurrentTeam,
    preEditTeam,
    editTeam
  }
}
